<template>
  <div class="role-list">
    <BasicTable @register="registerTable">
      <template #headerTop>
        <div class="text-lg font-bold my-2">角色管理</div>
      </template>
      <template #tableTitle>
        <div class="space-x-2">
          <a-button type="primary" @click="handleForm({})"> <Icon icon="i-fluent:add-12-filled" /> 新增角色 </a-button>
          <a-input
            v-model:value="searchParam.textSearch"
            placeholder="输入搜索内容"
            allow-clear
            @change="reload"
            style="width: 240px"
          >
            <template #suffix>
              <icon icon="ant-design:search-outlined" />
            </template>
          </a-input>
        </div>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handlePermission({ ...record })" :title="record.name">
          {{ record.name }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerFormModal" @success="handleSuccess" />
    <PermissionConfig @register="registerPermissionModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts">
  export default defineComponent({
    name: 'ViewsTbRoleList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, reactive } from 'vue';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { Icon } from '/@/components/Icon';
  import InputForm from './form.vue';
  import PermissionConfig from './permissionConfig.vue';
  import { getRoleList, deleteRole } from '/@/api/tb/role';
  import type { Recordable } from '/@/types';

  const { createConfirm, showMessage } = useMessage();

  const searchParam = reactive({
    textSearch: '',
  });

  const tableColumns: BasicColumn[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      align: 'left',
      fixed: 'left',
      slot: 'firstColumn',
      ellipsis: false,
    },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'ant-design:safety-outlined',
        title: '配置权限',
        onClick: handlePermission.bind(this, { ...record }),
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: '删除角色',
        onClick: handleDelete.bind(this, { ...record }),
      },
    ],
  };

  const [registerFormModal, { openModal: openFormModal }] = useModal();
  const [registerPermissionModal, { openModal: openPermissionModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    rowKey: (record) => record.roleId?.id || record.roleId,
    api: getRoleList,
    beforeFetch: wrapFetchParams,
    defSort: { sortProperty: 'createdTime', sortOrder: 'DESC' },
    columns: tableColumns,
    actionColumn: actionColumn,
    showTableSetting: false,
    useSearchForm: false,
    canResize: true,
  });

  function wrapFetchParams(param: any) {
    return {
      ...param,
      textSearch: searchParam.textSearch,
    };
  }

  function handleForm(record: Recordable) {
    openFormModal(true, record);
  }

  function handlePermission(record: Recordable) {
    openPermissionModal(true, record);
  }

  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'error',
      title: `确定删除角色[${record.name}]吗？`,
      content: '删除后角色及其关联的权限配置将无法恢复。',
      centered: false,
      okText: '删除',
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        const roleId = record.roleId?.id || record.roleId;
        if (!roleId) {
          showMessage('删除角色失败：缺少角色 ID', 'error');
          return;
        }
        try {
          await deleteRole(roleId);
          showMessage(`角色 [${record.name}] 已成功删除`, 'success');
          reload();
        } catch (error: any) {
          const errorMessage = error?.message || error?.data?.message || '未知错误';
          showMessage(`删除角色失败: ${errorMessage}`, 'error');
        }
      },
    });
  }

  function handleSuccess() {
    reload();
  }
</script>
<style lang="less">
  .role-list {
  }
</style>
